<?php
require_once 'CMS/Util.php';
require_once 'CMS/Mvc/BaseController.php';
require_once 'CMS/Mvc/BaseUserController.php';
require_once 'CMS/UserCommon.php';
require_once 'CMS/User.php';
require_once 'CMS/Language.php'; //include thu vien language

//Người tạo : Bùi Thành Nguyên - Team 4
//Module 	: Edit Category Module
//Chức năng	: Quản lý việc Edit các thuộc tính cho  module Category

class Category_ClickchangeController extends BaseUserController{

	public function init(){
		parent::init();
		$this->_helper->layout->disableLayout();
		$user = new User();
		$user->init();
		$user->check_login();
	}
	
	
	//Chức năng show các thuộc tính hiện tại cho người dùng
	public function indexAction(){
		
			/*========== Start Load Language ==========*/
			$language = new Language(APPLICATION_PATH . '/widgets/category/');
			if(isset($_SESSION['language']))
			{
				$language_id = $_SESSION['language'];
				$tbLanguage = new Language_Model_Language();
				$name = $tbLanguage->getNameLanguage($language_id);
				$language->load($name['name']);
			}
			else
				$language->load('Default');		
			/*========== End Load Language ==========*/
				
			/*========== Start Get Text ==============*/
			$this->view->textTitle 		= $language->get('text_title');
			$this->view->textOrder 		= $language->get('text_order');
			$this->view->textSave 		= $language->get('text_save');
			$this->view->textError1 	= $language->get('error1');
			$this->view->textError2 	= $language->get('error2');
			$this->view->textError4 	= $language->get('error4');
			$this->view->textError5 	= $language->get('error5');
			$this->view->textError6 	= $language->get('error6');
			$this->view->textError7 	= $language->get('error7');
			$this->view->textError8 	= $language->get('error8');
			/*========== End Text ==============*/
		
		//Start ------- Khởi tạo Parameter
		if(isset($_GET["url"]))
		{
			$this->view->url = $_GET["url"];
		}
		$path = APPLICATION_PATH."/widgets/category/";
		$tbSidebarModule = new  Category_Model_SidebarModule();
		//End ------- Khởi tạo Parameter
		
		//Start ------- Kiểm Tra file xml và truyền biến qua view
		$xmlconfig = new SimpleXMLElement($path."config.xml",null,true);//Read config.xml
		$user = new User();
			$user->init();
			$user->check_login();
			$hasmodify = $user->modifiy_widget($xmlconfig->name);
			if($hasmodify=="true")
			{
				if(isset($xmlconfig->name))
				{
					$module_supportonline = $tbSidebarModule->selectModuleByCode($xmlconfig->name);
				if(count($module_supportonline)>0)
                {
					$this->view->sort = $module_supportonline[0]["sort_order"];
					$this->view->name = $xmlconfig->name;
					$titleXML = 'title'.$name['name'];
					if(isset($xmlconfig->$titleXML))
					{
						$this->view->title = "".$xmlconfig->$titleXML;
					}
					else
					{
						if(isset($xmlconfig->titleDefault))
						{
			        		$this->view->title = "".$xmlconfig->titleDefault;
						}
			        	else
			        	{
			        		$this->view->error = 1 ;
			        	}
					}
                }
					else
					{
						$this->view->error = 1 ;
					}
				}
				else
				{
					$this->view->error = 1 ;
				}
		
				}
				else
				{
					$this->view->error = 2;
				}

		//End ------- Kiểm Tra file xml và truyền biến qua view
		
	}
	
	//thay đổi title và sort order của module
	public function editAction(){
		
		//check permission
		$path=APPLICATION_PATH . '/widgets/category/';
		$xmlconfig = new SimpleXMLElement($path."config.xml",null,true);
		$user = new User();
		$user->init();
		$user->check_login();
		$hasmodify = $user->modifiy_widget($xmlconfig->name);
		if($hasmodify!="true"){
			$response = -10;
			$this->_helper->json($response);
			return;
		}
		
		if(isset($_SESSION['language']))
		{
			$language_id = $_SESSION['language'];
			$tbLanguage = new Language_Model_Language();
			$name = $tbLanguage->getNameLanguage($language_id);
			
			if(isset($_GET["name"]))
			{
				$tbSidebarModule = new  Category_Model_SidebarModule();
				$module_lastest  = $tbSidebarModule->selectModuleByCode($_GET["name"]);
				if(count($module_lastest)>0)
				{
					if(isset($_GET["title"])&&(strlen($_GET["title"])>=5))
					{
						if(isset($_GET["limit"])&&(is_numeric($_GET["limit"]))&&($_GET["limit"]>0))
						{
							if(isset($_GET["sort"])&&(is_numeric($_GET["sort"]))&&($_GET["sort"]>=0))
							{
								if($module_lastest[0]["sort_order"] == $_GET["sort"])
								{
									$modules = 0;
								}
								else 
								{
									$modules = $tbSidebarModule->selectModuleBySortOrder($_GET["sort"]);
								}
								if(($modules==0)||count($modules)<=0)
								{
									$tbSidebarModule->updateModule($_GET["name"],$_GET["sort"]);//Save Sort_Order in DB
									
									//Start ------- Save title and limit in xml file
									$path = APPLICATION_PATH."/widgets/category/";
									$xmlconfig = new SimpleXMLElement($path."config.xml",null,true);//Read config.xml
									$titleXML = 'title'.$name['name'];
									$xmlconfig->$titleXML = $_GET['title'];
									file_put_contents($path."config.xml", $xmlconfig->asXML());
									//End ------- Save title and limit in xml file
									
									$data = 1;	
									
								}
								else
								{
									$data = -5;
								}
							}
							else
							{
								$data = -4;
							}
						}
						else 
						{
							$data = -3;
						}
					}
					else 
					{
						$data = -2;
					}
				}
				else
				{
					$data = -1;
				}
			}
			else 
			{
				$data = -1;
			}
		}
		else
			$data=-1;
		
		$this->_helper->json($data); 
	}
	
	//xử lý add category cha
	public function addpcategoryAction(){
		//Start ------- Khởi tạo Parameter
		$tbCategory= new Category_Model_Categories();
		//End ------- Khởi tạo Parameter
		
		//check permission
		$path=APPLICATION_PATH . '/widgets/category/';
		$xmlconfig = new SimpleXMLElement($path."config.xml",null,true);
		$user = new User();
		$user->init();
		$user->check_login();
		$hasmodify = $user->modifiy_widget($xmlconfig->name);
		if($hasmodify!="true"){
			$response = -10;
			$this->_helper->json($response);
			return;
		}
		
		$response="";
		if(count($_GET) && isset($_GET["nameDefault"]) && isset($_GET["catetype"]))
		{
			
			if (trim($_GET["nameDefault"]) == ""){
				$response = -4;
			}
			else
			{
				$tbLanguage = new Language_Model_Language();
				$languages = $tbLanguage->getAllLanguages();
				$lang['Default'] =  trim($_GET["nameDefault"]);
				foreach ($languages as $language){
					if(isset($_GET["name".$language['name']])){
						$lang[$language['name']] = trim($_GET["name".$language['name']]);
					}else{
						$lang[$language['name']] = '';						
					}
					
				}		
				$name=serialize($lang);
				$type=$_GET["catetype"];
				$code=$_GET["nameDefault"].$_GET["catetype"];
				$cate_data= array(
								"category_code" => $code,
								"category_name" => $name,
								"parent_id" => '0',
								"is_leaf" => '1',
								"type" => $type
								);
				$result=$tbCategory->addCategory($cate_data);
				if ($result==-1) //lỗi insert
				{
					$response=-3;
				}
				else
					$response=200;

			}
		}
		else
			$response=-1;
		$this->_helper->json($response);
	}
	
	//xử lý add category con
	public function addlcategoryAction(){
		//Start ------- Khởi tạo Parameter
		$tbCategory= new Category_Model_Categories();
		//End ------- Khởi tạo Parameter
		
		//check permission
		$path=APPLICATION_PATH . '/widgets/category/';
		$xmlconfig = new SimpleXMLElement($path."config.xml",null,true);
		$user = new User();
		$user->init();
		$user->check_login();
		$hasmodify = $user->modifiy_widget($xmlconfig->name);
		if($hasmodify!="true"){
			$response = -10;
			$this->_helper->json($response);
			return;
		}
		
		$response="";
		if(count($_GET) && isset($_GET["nameDefault"]) && isset($_GET["catetype"]) && isset($_GET["parent"]))
		{
			
			if (trim($_GET["nameDefault"]) == ""){
				$response = -6;
			}			
			else
			{
				
				$tbLanguage = new Language_Model_Language();
				$languages = $tbLanguage->getAllLanguages();
				$lang['Default'] =  trim($_GET["nameDefault"]);
				foreach ($languages as $language){
					if(isset($_GET["name".$language['name']])){
						$lang[$language['name']] = trim($_GET["name".$language['name']]);
					}else{
						$lang[$language['name']] = '';						
					}
					
				}
						
				$name=serialize($lang);
				$type=$_GET["catetype"];
				$code=$_GET["nameDefault"].$_GET["catetype"];
				$parent_id=$_GET["parent"];
				$cate_data= array(
								"category_code" => $code,
								"category_name" => $name,
								"parent_id" => $parent_id,
								"is_leaf" => '1',
								"type" => $type
								);
				$result=$tbCategory->addCategory($cate_data);
				//end insert leaf category
				if ($result==-1) //lỗi insert
				{
					$response=-3;
				}
				else
				{
					//$response=200;
					$parent_cate=$tbCategory->getCategoriesbyId($parent_id);
					//if category cha có is_leaf=0 thì ko làm gì cả
					if($parent_cate[0]['is_leaf']==0)
					{
						$response=200;
					}
					else//if category cha có is_leaf=1 thì update is_leaf=0 và update things tương ứng với category cha thành category con
					{
						$result=$tbCategory->updateIsLeaf($parent_id,0);
						if($result==-1) //lỗi update
						{
							$response=-4;
						}
						else //update things tương ứng nếu có
						{
							//$response=200;
							$tbThings=new Category_Model_Things();
							$things=$tbThings->getThingsByCategory($parent_id);
							if(count($things)>0)
							{
								//lấy thông tin leaf category vừa thêm
								$category=$tbCategory->getLeafCategoriesByParent($parent_id); //do chỉ có 1 category con
								//update things tương ứng
								$result=1;
								foreach($things as $thing)
								{
									if($tbThings->updateThingsCategory($thing["thing_id"],$category[0]["category_id"])==-1)//update lỗi
										$result=-1;
								}
								if($result==-1) //update lỗi
								{
									$response=-5;
								}
								else
									$response=200;
							}
							else //ko có thì ko làm gì cả
								$response=200;
						}
					}
				}
			}
		}
		else
			$response=-1;
		$this->_helper->json($response);
	}
	
	//xử lý edit category cha
	public function editpcategoryAction(){
		//Start ------- Khởi tạo Parameter
		$tbCategory= new Category_Model_Categories();
		//End ------- Khởi tạo Parameter
		
		//check permission
		$path=APPLICATION_PATH . '/widgets/category/';
		$xmlconfig = new SimpleXMLElement($path."config.xml",null,true);
		$user = new User();
		$user->init();
		$user->check_login();
		$hasmodify = $user->modifiy_widget($xmlconfig->name);
		if($hasmodify!="true"){
			$response = -10;
			$this->_helper->json($response);
			return;
		}
	
		$response="";
		if(count($_GET) && isset($_GET["nameDefault"]) && isset($_GET["cateid"]))
		{
			//kiểm tra tên đã sử dụng chưa
			if (trim($_GET["nameDefault"]) == ""){
				$response = -7;
			}
			else
			{
				//$response=$_GET["name"]."&".$_GET["cateid"];

				$tbLanguage = new Language_Model_Language();
				$languages = $tbLanguage->getAllLanguages();
				$lang['Default'] =  trim($_GET["nameDefault"]);
				foreach ($languages as $language){
					if(isset($_GET["name".$language['name']])){
						$lang[$language['name']] = trim($_GET["name".$language['name']]);
					}else{
						$lang[$language['name']] = '';						
					}
					
				}			
				$name=serialize($lang);				
				//update name
				$result=$tbCategory->updateName($_GET["cateid"],$name);
				if($result==-1)//lỗi update name
				{
					$response=-3;
				}
				else
				{
					if(isset($_GET["parent"]))//thay đổi parent
					{
						$parent_cate=$tbCategory->getCategoriesbyId($_GET["parent"]);//thông tin parent
						if($parent_cate[0]["is_leaf"]==0)//có nút con thì chỉ update parent_id cho category
						{
							$result=$tbCategory->updateParentId($_GET["cateid"],$_GET["parent"]);
							if($result==-1)//lỗi update
							{
								$response=-4;
							}
							else
							{
								$response=200;
							}
						}
						else //không có nút con thì update is_leaf của parent là 0, update things tương ứng nếu có trong parent vào category
						{
							$result=$tbCategory->updateParentId($_GET["cateid"],$_GET["parent"]);
							if($result==-1)//lỗi update
							{
								$response=-4;
							}
							else
							{
								//update is_leaf của parent
								$result=$tbCategory->updateIsLeaf($_GET["parent"],0);
								if($result==-1)//lỗi update
								{
									$response=-5;
								}
								else
								{
									//update things trong parent nếu có
									$tbThings=new Category_Model_Things();
									$things=$tbThings->getThingsByCategory($_GET["parent"]);
									if(count($things)>0)
									{
										//update things tương ứng
										$result=1;
										foreach($things as $thing)
										{
											if($tbThings->updateThingsCategory($thing["thing_id"],$_GET["cateid"])==-1)//update lỗi
												$result=-1;
										}
										if($result==-1) //update lỗi
										{
											$response=-6;
										}
										else
											$response=200;
									}
									else //ko có thì ko làm gì cả
									$response=200;
								}
							}
						}
					}
					
				}
			}
		}
		else
			$response=-1;
		$this->_helper->json($response);
	}
	
	
	//xử lý edit category con
	public function editlcategoryAction(){
		//Start ------- Khởi tạo Parameter
		$tbCategory= new Category_Model_Categories();
		//End ------- Khởi tạo Parameter
		
		//check permission
		$path=APPLICATION_PATH . '/widgets/category/';
		$xmlconfig = new SimpleXMLElement($path."config.xml",null,true);
		$user = new User();
		$user->init();
		$user->check_login();
		$hasmodify = $user->modifiy_widget($xmlconfig->name);
		if($hasmodify!="true"){
			$response = -10;
			$this->_helper->json($response);
			return;
		}
	
		$response="";
		if(count($_GET) && isset($_GET["nameDefault"]) && isset($_GET["cateid"]) && isset($_GET["parent"]))
		{
			$category=$tbCategory->getCategoriesbyId($_GET["cateid"]);//thông tin category cần sửa
			if (trim($_GET["nameDefault"]) == ""){
				$response = -7;
			}			
			else
			{
				$tbLanguage = new Language_Model_Language();
				$languages = $tbLanguage->getAllLanguages();
				$lang['Default'] =  trim($_GET["nameDefault"]);
				foreach ($languages as $language){
					if(isset($_GET["name".$language['name']])){
						$lang[$language['name']] = trim($_GET["name".$language['name']]);
					}else{
						$lang[$language['name']] = '';						
					}
					
				}		
				$name=serialize($lang);				
				//update name
				$result=$tbCategory->updateName($_GET["cateid"],$name);
				if($result==-1)//lỗi update name
				{
					$response=-3;
				}
				else if($category[0]["parent_id"]!=$_GET["parent"])//có thay đổi parent
				{
					//update old parent
					$old_parent=$tbCategory->getCategoriesbyId($category[0]["parent_id"]);//thông tin parent cũ
					$child_category=$tbCategory->getLeafCategoriesByParent($category[0]["parent_id"]);//category con của parent cũ
					if(count($child_category)==1) //chỉ có một con là category sắp edit, thì update is_leaf thành 1
						$tbCategory->updateIsLeaf($category[0]["parent_id"],1);
						
					//update new parent
					if($_GET["parent"]!="0")//nếu parent_id !=0
					{
						$parent_cate=$tbCategory->getCategoriesbyId($_GET["parent"]);//thông tin parent
						if($parent_cate[0]["is_leaf"]==0)//có nút con thì chỉ update parent_id cho category
						{
							$result=$tbCategory->updateParentId($_GET["cateid"],$_GET["parent"]);
							if($result==-1)//lỗi update
							{
								$response=-4;
							}
							else
							{
								$response=200;
							}
						}
						else //không có nút con thì update is_leaf của parent là 0, update things tương ứng nếu có trong parent vào category
						{
							//update parent_id
							$result=$tbCategory->updateParentId($_GET["cateid"],$_GET["parent"]);
							if($result==-1)//lỗi update
							{
								$response=-4;
							}
							else
							{
								//update is_leaf của parent
								$result=$tbCategory->updateIsLeaf($_GET["parent"],0);
								if($result==-1)//lỗi update
								{
									$response=-5;
								}
								else
								{
									//update things trong parent nếu có
									$tbThings=new Category_Model_Things();
									$things=$tbThings->getThingsByCategory($_GET["parent"]);
									if(count($things)>0)
									{
										//update things tương ứng
										$result=1;
										foreach($things as $thing)
										{
											if($tbThings->updateThingsCategory($thing["thing_id"],$_GET["cateid"])==-1)//update lỗi
												$result=-1;
										}
										if($result==-1) //update lỗi
										{
											$response=-6;
										}
										else
											$response=200;
									}
									else //ko có thì ko làm gì cả
									$response=200;
								}
							}
						}
					}
					else //parent_id=0, thành một category cấp 1
					{
						//update parent_id
							$result=$tbCategory->updateParentId($_GET["cateid"],$_GET["parent"]);
							if($result==-1)//lỗi update
							{
								$response=-4;
							}
							else
							{
								$response=200;
							}
					}
				}
			}
		}
		else
			$response=-1;
		$this->_helper->json($response);
	}
	
	//xử lý delete category con
	public function deleteAction(){
		
		/*========== Start Load Language ==========*/
			$language = new Language(APPLICATION_PATH . '/widgets/category/');
			if(isset($_SESSION['language']))
			{
				$language_id = $_SESSION['language'];
				$tbLanguage = new Language_Model_Language();
				$name = $tbLanguage->getNameLanguage($language_id);
				$language->load($name['name']);
			}
			else
				$language->load('Default');		
				//$textError2	= $language->get('error2');
			/*========== End Load Language ==========*/
		$path=APPLICATION_PATH . '/widgets/category/';
		$xmlconfig = new SimpleXMLElement($path."config.xml",null,true);
		$user = new User();
		$user->init();
		$user->check_login();
		$hasmodify = $user->modifiy_widget($xmlconfig->name);
		if($hasmodify=="true"){
		$response=200;
		if(count($_GET) && isset($_GET["id"]))
		{
			//Start ------- Khởi tạo Parameter
			$tbCategory= new Category_Model_Categories();
			$tbThings=new Category_Model_Things();
			//End ------- Khởi tạo Parameter
			
			$category=$tbCategory->getCategoriesbyId($_GET["id"]);//thông tin category delete
			if($category[0]["parent_id"]==0)//category cha
			{
				//$response=$language->get('text_deletesuccess');
				$response=200;
				$child_categories=$tbCategory->getLeafCategoriesByParent($_GET["id"]); //lấy các category con
				foreach($child_categories as $child_category)
				{
					$things=$tbThings->getThingsByCategory($child_category["category_id"]);
					if(count($things)>0)
					{
						$tbComments=new Category_Model_Comment();
						//delete comments tương ứng với things
						foreach($things as $thing)
						{
							$tbComments->deleteCommentsInThing($thing["thing_id"]);
						}
						//delete things tương ứng
						$result=$tbThings->deleteThingsInCategory($child_category["category_id"]); //delete things in child
						if($result==-1)
							//$response=$language->get('error13');
							$response=-13;
					}
					//delete child category
					$result=$tbCategory->deleteCategoryById($child_category["category_id"]);//delete child
					if($result==-1)
							$response=-13;
				}
				//delete category
				$result=$tbCategory->deleteCategoryById($_GET["id"]);
				if($result==-1)
					$response=-13;
			}
			else//category con
			{
				$response=200;
				$parent_cate=$tbCategory->getCategoriesbyId($category[0]["parent_id"]);//lấy category cha
				$child_category=$tbCategory->getLeafCategoriesByParent($category[0]["parent_id"]);
				if(count($child_category)==1) //chỉ có một con là category sắp delete, thì update is_leaf thành 1, update things vào category cha
				{
					//update is_leaf của parent
					$tbCategory->updateIsLeaf($category[0]["parent_id"],1);
					//update things vào parent
					$things=$tbThings->getThingsByCategory($_GET["id"]);
					if(count($things)>0)
					{
						//update things tương ứng
						$result=1;
						foreach($things as $thing)
						{
							if($tbThings->updateThingsCategory($thing["thing_id"],$category[0]["parent_id"])==-1)//update lỗi
								$result=-1;
						}
						if($result==-1) //update lỗi
						{
							//$response=$language->get('error12');
							$response=-12;
						}
					}
					//delete category
					$result=$tbCategory->deleteCategoryById($_GET["id"]);
					if($result==-1)
							$response=-13;
				}
				else //nếu có nhiều category con thì delete things trong category
				{
					$things=$tbThings->getThingsByCategory($_GET["id"]);
					if(count($things)>0)
					{
						$tbComments=new Category_Model_Comment();
						//delete comments tương ứng với things
						foreach($things as $thing)
							$tbComments->deleteCommentsInThing($thing["thing_id"]);
						//delete things tương ứng
						$result=$tbThings->deleteThingsInCategory($_GET["id"]);
						if($result==-1)
							$response=-13;
					}
					//delete category
					$result=$tbCategory->deleteCategoryById($_GET["id"]);
					if($result==-1)
							$response=-13;
				}
			}
		}
		else
		{
			//$response=$language->get('error3');
			$response=-3;
		}
		}
		else 
		{
			//$this->_helper->json($textError2);
			$response=-2;
		}
		$this->_helper->json($response);
	}
	
}